package com.gem.netty.message;

import com.gem.entity.Room;
import com.gem.enums.MessageColorType;
import com.gem.factory.game.GameFactory;
import com.gem.factory.room.RoomFactory;
import com.gem.netty.entity.ClientContent;
import com.gem.netty.session.GroupSessionFactory;
import com.gem.utils.R;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

/**
 * Author: Xhy
 * CreateTime: 2022-09-30 13:44
 * 开始游戏
 */
public class GameBeginMessage implements Message{


    @Override
    public void handler(ClientContent content) {

        ChannelHandlerContext ctx = content.getCtx();
        // 获取房间信息
        Room room = RoomFactory.get(content.getRoomId());

        // 只有房主可以开始游戏
        if (!content.getSendId().equals(room.getRoomOwnerId())){
            ctx.writeAndFlush(new TextWebSocketFrame(R.error().data("color",MessageColorType.SYSTEM_MESSAGE.type).message("只有房主可以开始游戏").type(content.getType()).toString()));
            return;
        }
        String roomId = room.getRoomId();
        // 开始游戏
        R r = GameFactory.start(roomId);
        if (!r.getState()){
            ctx.writeAndFlush(new TextWebSocketFrame(r.type(content.getType()).toString()));
            return;
        }
        // 告知其他用户开始游戏
        List<Channel> channels = GroupSessionFactory.getGroupSession().getMembersChannel(roomId);
        GameFactory.notifyUsers(channels,R.ok().data("color", MessageColorType.SYSTEM_MESSAGE.type).message("开始游戏").type(content.getType()),roomId);
        GameFactory.begin(roomId);
    }
}
